<template>
  <q-page class="q-pa-md" v-loading="loading">
    <div style="position: relative">
      <q-breadcrumbs class="q-mb-md" style="height: 40px; line-height: 40px">
        <q-breadcrumbs-el label="项目配置" />
      </q-breadcrumbs>
    </div>
    <div class="BasicConfiguration">
      <el-form
        style="width: 400px"
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="项目名称:" prop="title">
          <p v-if="!isEditor">{{ menuStore.currentProject.title }}</p>
          <el-input placeholder="请输入项目名称" v-else v-model="ruleForm.title" />
        </el-form-item>
        <el-form-item label="项目描述:">
          <p v-if="!isEditor">{{ menuStore.currentProject.description }}</p>
          <el-input v-else spellcheck="false" v-model="ruleForm.description" type="textarea" :rows="3" show-word-limit placeholder="请输入描述" maxlength="100" />
        </el-form-item>
        <el-form-item>
          <el-button :disabled="!userStatus" v-if="!isEditor" type="primary" @click="isEditor = true">编辑</el-button>
          <el-button v-else type="primary" @click="updateProjectInfo(ruleFormRef)">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div style="position: relative">
      <q-breadcrumbs class="q-mb-md" style="height: 40px; line-height: 40px">
        <q-breadcrumbs-el label="删除项目" />
      </q-breadcrumbs>
    </div>
    <div>
      <el-form
        style="width: 700px"
        ref="ruleFormRef1"
        :model="ruleForm1"
        :rules="rules1"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="*警告：">
          <p style="margin: 0;">此操作可能导致数据丢失。为防止意外,我们会要求您确认您的操作.</p>
          <p style="margin: 0">请输入"<span style="color: rgb(236,83,111)">确认删除</span>"以验证删除操作</p>
        </el-form-item>
        <el-form-item label="请输入:" prop="deleteName">
          <el-input v-model="ruleForm1.deleteName" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="*注意：">
          <p style="margin: 0;color: rgb(236,83,111)">删除项目将会删除项目下的数据、模型、建模及相关资源等所有内容.</p>
          <p style="margin: 0;color: rgb(236,83,111)">删除后项目不可恢复！请谨慎操作！</p>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="!userStatus" type="primary" @click="deleteProject(ruleFormRef1)">删除</el-button>
        </el-form-item>
      </el-form>
    </div>
  </q-page>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { deleteBadProject } from 'src/api/user'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router';
const router = useRouter()
import { useMenuStore } from 'src/stores/menu';
import {ElMessage} from "element-plus";
import {checkIsRepeatofProject, updateProject as updateProjectApi} from 'src/api/project'
const userStatus = JSON.parse(localStorage.getItem('user') || "{}").status;//判断用户是否是项目创建人或项目管理员
import {usernameAndEmailExist} from "src/api/system";
const menuStore = useMenuStore()
interface RuleForm {
  title: string
  description: string
}
interface RuleForm1 {
  deleteName: string
}
const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const ruleFormRef1 = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  title: '',
  description: '',
})
const ruleForm1 = reactive<RuleForm1>({
  deleteName: ''
})
const validateTitle = (rule: any, value: any, callback: any) => {
  if (!value && !ruleForm.description) {
    callback();
  }
  if( !value && ruleForm.description ){
    return callback(new Error('项目名称不能为空！'));
  }
  checkIsRepeatofProject({ project_name: value }).then( (res:any) =>{
    if( res.data.msg ){
      return callback(new Error(res.data.msg));
    }else {
      callback();
    }
  })
}
const rules = reactive<FormRules>({
  title: [{ required: true,validator: validateTitle, trigger: ['blur'] }],
})
const validateDeleteNameValue = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error(`请输入"确认删除"`))
  }
  if( value !== "确认删除" ){
    return callback(new Error(`请输入"确认删除"`))
  }else{
    callback();
  }
}
const rules1 = reactive<FormRules>({
  deleteName: [{ required: true, validator: validateDeleteNameValue, trigger: ['blur'] }],
})
let isEditor = ref(false);


//修改项目信息
const updateProjectInfo = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if( !ruleForm.title && !ruleForm.description ){
        isEditor.value = false;
        return;
      }
      const projectId = menuStore.currentProject.id;
      updateProjectApi(projectId, ruleForm).then((res) => {
        ruleForm.title = res.data.title;
        ruleForm.description = res.data.description;
        menuStore.setCurrentProject(res.data);
        menuStore.menuItems[0].title = res.data.title;
        menuStore.menuItems[0].description = res.data.description;
        isEditor.value = false;
      })
    }
  })
}
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}
const deleteProject = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      const id = menuStore.currentProject.id;
      deleteBadProject(id).then( res =>{
        ElMessage.success(`成功删除项目！`)
        router.push({ name: 'set-project' });
        menuStore.deleteMenuItems();
        // localStorage.removeItem('user');
      })
    }
  })
}
</script>
<style></style>
